import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:material_dialogs/dialogs.dart';
import 'package:material_dialogs/shared/types.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/model/options_item.dart';
import 'package:tracker/pages/home/setting/dialog/command_dialog_interface.dart';
import 'package:tracker/pages/home/setting/model/remote_setting_list_resp.dart';
import 'package:tracker/theme/app_theme.dart';

class LightAlarmDialog implements CommandDialogInterface {
  late StateSetter _newSetState;

  final GlobalKey<ScaffoldState> scaffoldKey;
  final RemoteSettingData remoteSettingData;

  // 回调函数
  final Function(String cmdContent)? onConfirm;

  LightAlarmDialog({
    required this.scaffoldKey,
    required this.remoteSettingData,
    this.onConfirm,
  }) {
    // 初始化选项列表
    List<dynamic> enumObjs = json.decode(remoteSettingData.cmdFormat ?? '')[0]['enumObjs'];
    for (var element in enumObjs) {
      final item = OptionsItem(label: element['value'], value: element['valueReal']);
      pickerOptions.add(item);
    }
  }

  int indexSelected = 0;

  final List<OptionsItem> pickerOptions = [];

  @override
  void show(BuildContext context) {
    return Dialogs.bottomMaterialDialog(
        context: context,
        isScrollControlled: true,
        customView: StatefulBuilder(builder: (newContext, newSetState) {
          _newSetState = newSetState;
          return Container(
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Colors.white,
                  Colors.grey.shade50,
                ],
              ),
              borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                // 标题行
                Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.all(10),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                          colors: [
                            AppTheme.themeConfig.primaryColor.withOpacity(0.15),
                            AppTheme.themeConfig.primaryColor.withOpacity(0.05),
                          ],
                        ),
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        Icons.wb_sunny,
                        color: AppTheme.themeConfig.primaryColor,
                        size: 24,
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Text(
                        remoteSettingData.cmdName ?? '',
                        style: TextStyle(
                          fontSize: 20,
                          color: AppTheme.themeConfig.primaryTextColor,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 20),
                // 提示信息
                Container(
                  padding: const EdgeInsets.all(14),
                  decoration: BoxDecoration(
                    color: Colors.orange.shade50,
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(
                      color: Colors.orange.shade200,
                      width: 1,
                    ),
                  ),
                  child: Row(
                    children: [
                      Icon(
                        Icons.info_outline,
                        color: Colors.orange.shade700,
                        size: 18,
                      ),
                      const SizedBox(width: 10),
                      Expanded(
                        child: Text(
                          remoteSettingData.remark ?? '',
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.grey[700],
                            height: 1.4,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 20),
                // 选择器
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(16),
                    border: Border.all(
                      color: AppTheme.themeConfig.primaryColor.withOpacity(0.2),
                      width: 1,
                    ),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.05),
                        blurRadius: 8,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: Row(
                    children: [
                      Text(
                        '光感报警',
                        style: TextStyle(
                          fontSize: 16,
                          color: AppTheme.themeConfig.primaryTextColor,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      const Spacer(),
                      GestureDetector(
                        onTap: () {
                          // 显示picker
                          Picker picker = Picker(
                            adapter: PickerDataAdapter(
                              data: pickerOptions.map((e) => PickerItem(text: Text(e.label), value: e.value)).toList(),
                            ),
                            changeToFirst: true,
                            cancelText: '取消',
                            confirmText: '确定',
                            cancelTextStyle: const TextStyle(color: Colors.grey, fontSize: 16),
                            textAlign: TextAlign.left,
                            textStyle: const TextStyle(color: Colors.black, fontSize: 18),
                            selectedTextStyle: TextStyle(color: AppTheme.themeConfig.primaryColor, fontSize: 18),
                            columnPadding: const EdgeInsets.all(8.0),
                            onConfirm: (Picker picker, List value) {
                              XLogger.info('value: ${value}');
                              XLogger.info('picker.getSelectedValues(): ${picker.getSelectedValues()}');
                              newSetState(() {
                                indexSelected = value[0];
                              });
                            },
                          );
                          picker.selecteds = [indexSelected];
                          picker.showModal(context);
                        },
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              colors: [
                                AppTheme.themeConfig.primaryColor.withOpacity(0.1),
                                AppTheme.themeConfig.primaryColor.withOpacity(0.05),
                              ],
                            ),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Row(
                            children: [
                              _buildPickerTriggerText(),
                              const SizedBox(width: 6),
                              Icon(
                                Icons.keyboard_arrow_down,
                                color: AppTheme.themeConfig.primaryColor,
                                size: 20,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 24),
              ],
            ),
          );
        }),
        customViewPosition: CustomViewPosition.BEFORE_TITLE,
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
            },
            style: TextButton.styleFrom(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
            ),
            child: const Text(
              '取消',
              style: TextStyle(color: Colors.grey, fontSize: 16, fontWeight: FontWeight.w600),
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 8),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  AppTheme.themeConfig.primaryColor,
                  AppTheme.themeConfig.primaryColor.withOpacity(0.8),
                ],
              ),
              borderRadius: BorderRadius.circular(12),
              boxShadow: [
                BoxShadow(
                  color: AppTheme.themeConfig.primaryColor.withOpacity(0.3),
                  blurRadius: 8,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: TextButton(
              onPressed: () {
                // 发送指令
                Navigator.pop(context);
                onConfirm?.call(getCommand());
              },
              style: TextButton.styleFrom(
                padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                backgroundColor: Colors.transparent,
              ),
              child: const Text(
                '发送指令',
                style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w700),
              ),
            ),
          ),
        ]);
  }

  _buildPickerTriggerText() {
    if (pickerOptions.isNotEmpty && indexSelected >= 0 && indexSelected < pickerOptions.length) {
      return Text(
        '${pickerOptions[indexSelected].label}',
        style: TextStyle(fontSize: 16, color: AppTheme.themeConfig.primaryColor),
      );
    }
    return Text('');
  }

  @override
  String getCommand() {
    // 拼接指令内容
    final content = pickerOptions[indexSelected].value;
    return '${remoteSettingData.cmdCode},${content}';
  }

  @override
  void updateCmdContent(String cmdContent) {
    if (cmdContent.isNotEmpty) {
      // 解析指令内容
      final cmdContentList = cmdContent.split(',');
      if (cmdContentList.length == 2) {
        indexSelected = pickerOptions.indexWhere((element) => element.value == cmdContentList[1]);
      }
    }
  }
}
